package com.jiaoyou.baojian.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.adapter.GoodsAdapter;
import com.jiaoyou.baojian.entity.GoodEntity;
import com.jiaoyou.baojian.entity.pay.PayResponse;
import com.jiaoyou.baojian.entity.pay.PayResult;
import com.jiaoyou.baojian.entity.pay.SubmitResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.BaofangCallback2;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.otto.AppBus;
import com.jiaoyou.baojian.otto.Event;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class RechargeActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.goods)
    RecyclerView goods;
    @BindView(R.id.alipay)
    Button alipay;
    @BindView(R.id.wxpay)
    Button wxpay;

    private static final int SDK_PAY_FLAG = 1;

    private List<GoodEntity> goodList;
    private GoodsAdapter goodsAdapter;
    private SubmitResponse submitResponse;
    private PayResponse payResponse;
    private boolean aliPay = true;

    public static void show(Context context){
        Intent intent = new Intent(context, RechargeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        setTitle("充值");

        goodList = new ArrayList<>();
        goodsAdapter = new GoodsAdapter();
        goods.setLayoutManager(new GridLayoutManager(this, 3));
        goods.setAdapter(goodsAdapter);
        goodsAdapter.setNewData(goodList);
        goodsAdapter.setEmptyView(getEmptyView());
        goodsAdapter.notifyDataSetChanged();

        getData();
    }

    private void getData() {
        Api.getInstance().getGoods(new BaofangCallback2<GoodEntity>(){

            @Override
            public void onFailure(Call<BaseResponse<GoodEntity>> call, Throwable t) {

            }

            @Override
            public void onSuccess(List<GoodEntity> list) {
                goodsAdapter.setNewData(list);
                goodsAdapter.setOnItemClickListener(RechargeActivity.this);
                goodsAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getContentView() {
        return R.layout.activity_recharge;
    }

    @OnClick({R.id.alipay, R.id.wxpay})
    public void onViewClicked(View view) {
        if(goodsAdapter.getSelected() < 0)
            return;
        switch (view.getId()) {
            case R.id.alipay:
                aliPay = true;
                waiting("正在创建订单");
                tradeSubmit();
                break;
            case R.id.wxpay:
                aliPay = false;
                toast("等待下一版接入");
                break;
        }
    }

    private void tradeSubmit() {
        Api.getInstance().tradeSubmit(goodsAdapter.getItem(goodsAdapter.getSelected()).getSkuId(), 1,
                new BaofangCallback<SubmitResponse>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        stopWaiting();
                        toast("创建订单失败：" + t.getLocalizedMessage());
                    }

                    @Override
                    public void onSuccess(SubmitResponse response) {
                        stopWaiting();
                        submitResponse = response;
                        waiting("确认付款信息...");
                        tradePay();
                    }
                });
    }

    private void tradePay(){
        Api.getInstance().tradePay(new long[]{submitResponse.getTradeList().get(0).getId()},
                new BaofangCallback<PayResponse>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                stopWaiting();
                toast("获取付款信息失败：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(PayResponse response) {
                stopWaiting();
                payResponse = response;
                waiting("提交付款...");
                if(aliPay){
                    appAlipay();
                } else {

                }
            }
        });
    }

    private void appAlipay(){
        Api.getInstance().appAlipay(payResponse.getEctoolsPaymentDO().getPayment_id(),
                new BaofangCallback<String>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                stopWaiting();
                toast("提交付款失败：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(final String response) {
                stopWaiting();
                waiting("调起支付宝付款...");
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(RechargeActivity.this);
                        Map<String, String> result = alipay.payV2(response, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    stopWaiting();
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toast("支付成功");
                        AppBus.getInstance().post(Event.EVENT_ALIPAY);
                        AppBus.getInstance().post(Event.EVENT_REFRESH_USERINFO);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        toast("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private View getEmptyView() {
        TextView textView = new TextView(this);
        textView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        textView.setGravity(Gravity.CENTER);
        textView.setText("加载中");
        return textView;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        goodsAdapter.select(position);
        goodsAdapter.notifyDataSetChanged();
    }
}
